余烬缀记

GraphQL 查询语句笔记

edited on:

image_20190326170936.png

学习 GraphQL 时的一些笔记

# 编写 GraphQL 查询语句

每一个查询语句都应该拥有一个操作类型以及操作名称

目前操作类型有:querymutationsubscription

操作名称和为函数命名是同样的道理

query QueryName {
    node {
        name
        friends
    }
}

# 使用变量

变量使用$来作为前缀,亦可以理解为声明

query QueryName($id: Int!) {
    node($id) {
        name
        friends
    }
}

上述查询中$id便是声明的变量,Int为类型,如果不加!便代表这是可选的,加了便是必需的

# 默认变量

query QueryName($id: !Int = 120547) {
    node($id) {
        name
        friends
    }
}

# 指令

指令能动态的改变结果

query QueryName($id: !Int = 120547, $withSex: Boolean!, $withFamily: Boolean!) {
    node($id) {
        name
        # 字段的使用方式
        sex@include(if: $withSex)
        # 片段使用
        family(@include(if: $withFamily)) {
            name
        }
    }
}

下列是每个 GraphQL 都应实现支持的指令:

  • @include(if: Boolean)参数为true时包含这个字段或者片段
  • @skip(if: Boolean)true时跳过该字段

# 编写变更语句

使用操作类型mutation

mutation CreateComment($userId: Int, $content: String) {
	# 假装提交一个评论
    createComment(id: $userId, content: $content) {
        status
        message
    }
}

# 关于变更语句和查询语句中的字段执行顺序

查询字段时,是进行并行执行的

变更字段时,是线性执行,从上到下